const fs = require('fs').promises;
const path = require('path');

class FileHandler {
  constructor(options = {}) {
    this.dataDir = options.dataDir || 'data';
    this.maxRecords = options.maxRecords || 1000;
    this.filename = 'ip_records.json';
    this.init();
  }

  async init() {
    try {
      await fs.mkdir(this.dataDir, { recursive: true });
    } catch (error) {
      console.error('创建数据目录失败:', error);
    }
  }

  async readIpData() {
    try {
      const filePath = path.join(this.dataDir, this.filename);
      const data = await fs.readFile(filePath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      if (error.code === 'ENOENT') {
        return [];
      }
      throw error;
    }
  }

  async appendIpData(ipData) {
    try {
      const filePath = path.join(this.dataDir, this.filename);
      let records = await this.readIpData();
      
      if (!Array.isArray(records)) {
        records = [];
      }

      records.push(ipData);

      // 限制记录数量
      if (records.length > this.maxRecords) {
        records = records.slice(-this.maxRecords);
      }

      await fs.writeFile(filePath, JSON.stringify(records, null, 2));
      return true;
    } catch (error) {
      console.error('保存IP数据失败:', error);
      throw error;
    }
  }
}

module.exports = { FileHandler }; 